<?php namespace App\Http\Controllers\Api;

use App\Activity;
use App\Doctors;
use App\Exceptions\DataException;
use App\Exceptions\NotFoundException;
use App\Exceptions\SecurityException;
use App\Questions;
use App\Services\haoting;
use App\Services\UserManager;
use App\Services\Wechat\WechatModelMsg;
use App\Services\YunPian;
use App\User;
use App\UserActivity;
use App\UserXDoctor;
use App\VerifyPhone;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Session;
use Log;

class UserController extends ApiController
{
    public function setUserInfo(Guard $guard,Request $request){
        $realname = Input::get('realname');
        $sex      = Input::get('sex');
        $phone    = Input::get('phone');
        $birthday = Input::get('birthday');

        /** @var User $user */
        $user = UserManager::isLogin($request);
        $thatUserInfo = $user->userInfo;

        if(!is_null($realname))$thatUserInfo->realname = $realname;
        if(!is_null($sex))$thatUserInfo->sexual = $sex;
        if(!is_null($phone))$thatUserInfo->phone = $phone;
        if(!is_null($birthday))$thatUserInfo->birthday = $birthday;
        if(!is_null($thatUserInfo->realname) && !is_null($thatUserInfo->phone))
            $thatUserInfo->status = 1;

        $thatUserInfo->save();

        return $this->buildResponse(trans('设置成功'),$thatUserInfo);
    }

    public function addDoctor(Guard $guard,Request $request){
        $id           = !is_null(Input::get('id')) ? Input::get('id') : 0;
        $name         = Input::get('name');
        $sex          = Input::get('sex');
        $photo        = Input::get('photo');
        $subject      = Input::get('subject');
        $station      = Input::get('station');
        $introduction = Input::get('introduction');
        $isWork       = Input::get('iswork');
        $fee          = Input::get('fee');
        $hospital_id  = Input::get('hospital_list');
        $dep_id       = Input::get('dep_list');
        $phone        = Input::get('phone');

        $admin = UserManager::isLogin($request);
        if(!$admin)
            throw new SecurityException(SecurityException::LoginFirst);

        /** @var User $admin */
        if((int)$admin->role < 3)
            throw new SecurityException(SecurityException::NoPermission);

        if(!preg_match("/^(1[34578])[0-9]{9}$/", trim($phone)))
            return response()->json(['level' => 'error','message' => '请正确输入手机号码！']);

        $isPhone = Doctors::wherePhone($phone)->first();

        $thatDoctor = Doctors::find($id);

        if($isPhone && ($thatDoctor && $thatDoctor->id != $isPhone->id))
            return response()->json(['level' => 'error','message' => '该手机号已被他人使用']);


        if(!$thatDoctor){
            $thatDoctor = new Doctors();

            if($isPhone)
                return response()->json(['level' => 'error','message' => '该手机号已被他人使用']);
        }

        if(!is_null($name))$thatDoctor->doc_name = $name;
        if(!is_null($sex))$thatDoctor->sexual = $sex;
        if(!is_null($photo))$thatDoctor->doc_img = $photo;
        if(!is_null($subject))$thatDoctor->subject = $subject;
        if(!is_null($station))$thatDoctor->station = $station;
        if(!is_null($introduction))$thatDoctor->introduction = $introduction;
        if(!is_null($isWork))$thatDoctor->is_work = $isWork;
        if(!is_null($fee))$thatDoctor->fee = $fee;
        if(!is_null($hospital_id))$thatDoctor->hospital_id = $hospital_id;
        if(!is_null($dep_id))$thatDoctor->dep_id = $dep_id;
        if(!is_null($phone))$thatDoctor->phone = $phone;

        $thatDoctor->save();



        return $this->buildResponse(trans('添加成功'),$thatDoctor);
    }

    public function delDoctor(Guard $guard,Request $request){
        $admin = UserManager::isLogin($request);
        if(!$admin)
            throw new SecurityException(SecurityException::LoginFirst);

        /** @var User $admin */
        if((int)$admin->role < 3)
            throw new SecurityException(SecurityException::NoPermission);

        $id = Input::get('id');

        /** @var Doctors $thatDoctor */
        $thatDoctor = Doctors::find($id);

        if(!$thatDoctor)
            throw new NotFoundException(NotFoundException::DataNotFound);

        $thatDoctor->delete();

        return $this->buildResponse(trans('删除成功'));
    }

    public function followDoctor(Guard $guard,Request $request){
        $user = UserManager::isLogin($request);
        if(!$user)
            throw new SecurityException(SecurityException::LoginFirst);

        /** @var User $user */

        $docId = Input::get('doc_id');

        $thatDoctor = Doctors::whereUserId($docId)->first();

        if(!$thatDoctor)
            throw new NotFoundException(NotFoundException::UserNotFound);

        /** @var UserXDoctor $hasFollow */
        $hasFollow = UserXDoctor::whereUserId($user->id)->whereDoctorId($docId)->first();

        $state = null;
        if($hasFollow){
            $hasFollow->delete();
            $state = 'cancel';
        }else{
            $hasFollow            = new UserXDoctor();
            $hasFollow->user_id   = $user->id;
            $hasFollow->doctor_id = $docId;
            $hasFollow->save();

            $state = 'follow';
        }

        return $this->buildResponse(trans('设置成功'),$state);
    }

    public function addQuestion(Guard $guard,Request $request){
        $user = UserManager::isLogin($request);
        if(!$user)
            throw new SecurityException(SecurityException::LoginFirst);

        /** @var User $user */

        $docId    = Input::get('doc_id');
        $question = Input::get('question');

        if(mb_strlen($question) < 6)
            throw new DataException(DataException::QuestionIsTosloft);


        $thatDoctor =Doctors::whereUserId($docId)->first();
        if(!$thatDoctor)
            throw new NotFoundException(NotFoundException::UserNotFound);

        $questionModel            = new Questions();
        $questionModel->user_id   = $user->id;
        $questionModel->doctor_id = $docId;
        $questionModel->question  = $question;
        $questionModel->save();

        WechatModelMsg::sendQuestionMsgToDoctor($questionModel,route('M.Doctor.myQuestions'));

        return $this->buildResponse(trans('提问成功'),$questionModel);
    }

    public function followDocByQrcode(Guard $guard,Request $request){
        $docId = Input::get('doc_id');
        $user = UserManager::isLogin($request);
        if(!$user){
            Session::put('doc_id', $docId);
            return redirect(route('Api.Auth.weixinLogin').'?state=follow');
        }else{
            /** @var User $user */
            if(!is_null($docId)){
                Log::error('2===>'.$docId);
                $doctor = Doctors::whereUserId($docId)->first();
                if($doctor){
                    Log::error('3===>'.$docId);
                    /** @var UserXDoctor $hasFollow */
                    $hasFollow = UserXDoctor::whereUserId($user->id)->whereDoctorId($docId)->first();

                    if(!$hasFollow){
                        $hasFollow            = new UserXDoctor();
                        $hasFollow->user_id   = $user->id;
                        $hasFollow->doctor_id = $docId;
                        $hasFollow->save();
                    }

                    return redirect(route('M.Home.newDoctorDetail',['id'=>$doctor->id]));
                }else{
                    return redirect(route('M.Home.newDoctorList'));
                }

            }else{
                return redirect(route('M.Home.newDoctorList'));
            }
        }
    }

    /**
     * 获取用户参与的活动
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserJoinActivity(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $limit = !is_null($request->get('limit')) ? $request->get('limit') : 10;
        $page  = !is_null($request->get('page')) ? $request->get('page') : 0;

        /** @var UserActivity $userJoinActivity */
        $userJoinActivityList = UserActivity::whereUserId($user->id)->whereStatus(1)->orderBy('created_at','desc')->offset($limit * $page)->limit($limit)->get();
        if(count($userJoinActivityList) > 0){
            foreach($userJoinActivityList as $userJoinActivity){
                /** @var Activity $thisActivity */
                $thisActivity = Activity::whereId($userJoinActivity->activity_id)->whereStatus(1)->first();
                if($thisActivity){
                    $thisActivity->img_url = route('Api.Image.Show',['id' => $thisActivity->img_id]);
                    $userJoinActivity->activity_info = $thisActivity;
                }else{
                    $userJoinActivity->activity_info = null;
                }

                $userActivity = UserActivity::whereActivityId($userJoinActivity->activity_id)->whereStatus(1)->count();

                $userJoinActivity->join_num = $userActivity;
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $userJoinActivityList]);
    }

    /**
     * 发送验证码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function sendVerificationCode(Request $request)
    {
        $phone = $request->get('phone');
        $isAttact = VerifyPhone::whereIp($request->ip())->orderBy('created_at', 'desc')->first();
        $isAttact_count = VerifyPhone::whereIp($request->ip())->count();

        if(!preg_match("/^(1[34578])[0-9]{9}$/", $phone))
            return response()->json(['level' => 'error','message' => '请正确输入手机号码！']);

        if ($isAttact_count > 3 && $isAttact->created_at->timestamp + 60 > time())
            return response()->json(['level' => 'error', 'message' => '请等待60秒后再发送']);
        if ($isAttact_count > 24 && $isAttact->created_at->timestamp + 60 * 60 * 24 > time())
            return response()->json(['level' => 'error', 'message' => '不允许访问！']);

        $result = VerifyPhone::wherePhone($phone)->orderBy('created_at', 'desc')->first();
        if ($result && 60 + $result->created_at->timestamp > time())
            return response()->json(['level' => 'error', 'message' => '请等待60秒后再发送']);

        VerifyPhone::wherePhone($phone)->delete();

        $VerifyCodeByPhone = new VerifyPhone();
        $VerifyCodeByPhone->phone = $phone;
        $VerifyCodeByPhone->verify_code = sprintf("%04d", rand(1000, 9999));
        $VerifyCodeByPhone->ip = $request->ip();
        $VerifyCodeByPhone->ensure_session = '';

        $send = new haoting();
        $send->sendBasicSmsWithCode($phone, $VerifyCodeByPhone->verify_code);

        $VerifyCodeByPhone->save();

        return response()->json(['level' => 'success', 'message' => trans('验证码发送成功')]);
    }
}